<template>
  <div>
    <div class="map_dialog">
      <div class="map_left">
        <div id="map_box" ref="map"></div>
      </div>
      <div class="map_right">
        <div class="map_title">
          <div class="map_title_left">结果列表</div>
          <div class="map_title_right">
            <el-button
              class="bin_button"
              size="medium"
              icon="el-icon-upload"
              @click="clickExport"
              >结果导出</el-button
            >
          </div>
        </div>
        <div class="map_list_wrap">
          <div class="map_list">
            <el-collapse class="ship_collapse">
              <el-collapse-item
                v-for="item in mapShipList"
                :key="item.dataColumnId"
              >
                <template slot="title">
                  <div class="map_items_title">
                    <div class="items_name">
                      {{ item.dataInfo[NameColumn] }}
                    </div>
                    <div class="items_title_icons">
                      <div
                        class="title_icon_edit"
                        v-show="!item.isEditIng"
                        @click.stop="onEditShipItemFn(item)"
                      >
                        <el-tooltip
                          class="item"
                          effect="dark"
                          content="编辑"
                          placement="top"
                        >
                          <div class="el-icon-edit"></div>
                        </el-tooltip>
                      </div>
                      <div
                        class="title_icon_del"
                        @click.stop="onRemoveShipItemFn(item)"
                      >
                        <el-tooltip
                          class="item"
                          effect="dark"
                          content="删除"
                          placement="top"
                        >
                          <div class="el-icon-delete-solid"></div>
                        </el-tooltip>
                      </div>
                    </div>
                  </div>
                </template>
                <div class="map_items_content">
                  <div
                    class="content_items"
                    v-for="(v, i) in item.nameArr"
                    :key="i"
                  >
                    <div class="items_name">{{ v }}</div>
                    <div class="items_val">
                      <el-input
                        v-model="item.dataInfo[v]"
                        class="ship_input"
                        :disabled="!item.isEditIng"
                        placeholder="请输入内容"
                      >
                      </el-input>
                    </div>
                  </div>
                  <div class="content_items_btns" v-show="item.isEditIng">
                    <el-button
                      class="bin_button"
                      size="mini"
                      @click="onShipEditCancelFn(item)"
                      >取消</el-button
                    >
                    <el-button
                      class="bin_button"
                      size="mini"
                      @click="onShipEditSubmitFn(item)"
                      >确认1</el-button
                    >
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </div>
    </div>
    <div id="ship_popup"></div>
    <!-- 导出弹窗 -->
    <el-dialog
      v-zsdialogDrag
      :closeOnClickModal="false"
      title="导出"
      :visible.sync="daochuDialogFlag"
      class="bin_dialog dialog-1000"
      width="50%"
      top="10vh"
    >
      <dao-chu
        v-if="daochuDialogFlag"
        :daoruTableId="leftSelectId"
        :rongheTableId="hisTableId"
        :selected="mainTableSelectedId"
        @close="daochuDialogFlag = false"
      ></dao-chu>
    </el-dialog>
  </div>
</template>

<script>
import "ol/ol.css";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorTile from "ol/source/VectorTile";
import VectorSource from "ol/source/Vector";
import Overlay from "ol/Overlay";
import OSM from "ol/source/OSM";
import XYZ from "ol/source/XYZ";
import MVT from "ol/format/MVT";
import TileWMS from "ol/source/TileWMS";
import { Map, View, Feature } from "ol";
import { Style, Stroke, Fill, Icon, Text, Circle } from "ol/style";
import { Polygon, MultiPolygon, Point, LineString } from "ol/geom";
import geomCircle from "ol/geom/Circle";
import { getVectorContext } from "ol/render";
import {
  ScaleLine,
  defaults as defaultControls,
  MousePosition,
} from "ol/control";
import { format } from "ol/coordinate";
import { transform, toLonLat } from "ol/proj";
import { defaults } from "ol/interaction";
import shipPng from "../../../../assets/jianchuan-blue.png";
import daoChu from "@/components/daochuNew.vue";

export default {
  name: "newmapDialog",
  components: { daoChu },
  props: {
    lon: {
      //经度表头
      type: String,
    },
    lat: {
      //纬度表头
      type: String,
    },
    NameColumn: {
      //名称表头
      type: String,
    },
    mapShipListobj: {
      type: Object,
    },
    objarrr: {
      type: Object,
    },
    maxLongitude: {
      type: String,
    },
    minLongitude: {
      type: String,
    },
    maxLatitude: {
      type: String,
    },
    minLatitude: {
      type: String,
    },
  },

  data() {
    return {
      mapShipListName: [],
      mapShipList: [],
      centerCoodinate: [110, 32],
      mapInstance: null,
      popupObj: null,
      shipLayer: null,
      daochuDialogFlag: false,
      leftSelectId: "",
      fusionId: "",
      mainTableSelectedId: [],
      hisTableId: "",
    };
  },
  mounted() {
    this.$nextTick(() => {
      if (!this.$refs.map) {
        console.error("地图容器未正确初始化，请检查模板是否渲染");
        return;
      }
      this.initMapFn();
    });
    // correlationJudgmentHisData
    // let nameArr = this.mapShipListobj.correlationJudgmentHisColumn.map(
    //   (item) => {
    //     return (item.columnName = item.columnName);
    //   }
    // );

    // this.mapShipListobj.correlationJudgmentHisData.map((item) => {
    //   item.dataInfo = JSON.parse(item.dataInfo);
    //   item.nameArr = nameArr;
    // });

    // this.mapShipList = this.mapShipListobj.correlationJudgmentHisData;
    // this.mapShipList.forEach((item) => {
    //   item.isEditIng = false;
    // });
  },
  watch: {
    mapShipListobj: {
      handler(newVal) {
        if (!newVal || !newVal.correlationJudgmentHisData) return;

        let nameArr = newVal.correlationJudgmentHisColumn.map(
          (item) => item.columnName
        );
        // 遍历每条数据
        newVal.correlationJudgmentHisData.forEach((item) => {
          // 只有 dataInfo 是字符串时才解析
          if (typeof item.dataInfo === "string") {
            try {
              item.dataInfo = JSON.parse(item.dataInfo);
            } catch (e) {
              console.warn("JSON.parse 失败:", e, item.dataInfo);
              item.dataInfo = {}; // 解析失败则设为空对象
            }
          }
          // 添加字段
          item.nameArr = nameArr;
          item.isEditIng = false;
        });
        // 更新本地数据
        this.mapShipList = newVal.correlationJudgmentHisData;
        // ✅ 新增：如果地图已存在，直接更新点
        if (this.mapInstance && this.shipLayer) {
          this.forEachShipPointToMapFn();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    clickExport() {
      this.mainTableSelectedId = this.mapShipList.map((e) => e.id);
      console.log(this.mapShipListobj);
      if (this.mainTableSelectedId.length > 0) {
        this.hisTableId = this.objarrr.correlationJudgmentTableId;
        this.daochuDialogFlag = true;
      } else {
        this.$message({
          message: "暂无数据~",
          type: "warning",
        });
      }
    },
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~功能项的 ~~~~~~~~~~~~~~~~~~~~~~~~~~
    // 修改船只信息
    onEditShipItemFn(item) {
      console.log(item, "item");
      if (item.isEditIng) {
        return;
      }
      let flag = this.mapShipList.some((item22) => {
        return item22.isEditIng;
      });
      if (flag) {
        this.$message({
          message: "请先完成其他船只的修改~",
          type: "warning",
        });
      } else {
        this.mapShipList = this.mapShipList.map((item22) => {
          return { ...item22, isEditIng: item22.id === item.id };
        });
      }
    },
    // 删除船只信息
    onRemoveShipItemFn(item) {
      this.$confirm("此操作将删除该船只, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.mapShipList = this.mapShipList.filter((ele) => {
          return ele.id !== item.id;
        });
        console.log(this.mapShipList, "171");
        this.onDelMapShipInfoFn(item);
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
    // 修改船只下的确认按钮
    onShipEditSubmitFn(item) {
      console.log(item, "item");
      let newItem = { ...item, shipInfo: item.dataInfo, isEditIng: false };
      this.mapShipList = this.mapShipList.map((item22) => {
        if (item22.id === item.id) {
          return newItem;
        } else {
          return item22;
        }
      });
      console.log(this.mapShipList, "this.mapShipList");
      this.onUpdateMapShipInfoFn(newItem);
    },
    // 修改船只下的取消按钮
    onShipEditCancelFn(item) {
      let newItem = { ...item, editShipInfo: item.dataInfo, isEditIng: false };
      this.mapShipList = this.mapShipList.map((item22) => {
        console.log(item22.id, item.id);
        if (item22.id === item.id) {
          return newItem;
        } else {
          return item22;
        }
      });
    },
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~地图项的 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //   初始化地图
    initMapFn() {
      this.$nextTick(() => {
        if (!this.mapInstance) {
          if (this.maxLongitude) {
            let lonCenter =
              (Number(this.maxLongitude) + Number(this.minLongitude)) / 2;
            let latCenter =
              (Number(this.maxLatitude) + Number(this.minLatitude)) / 2;
            this.centerCoodinate = [lonCenter, latCenter];
          }

          console.log(
            this.centerCoodinate,
            "加载地图初始化this.centerCoodinate"
          );
          this.mapInstance = new Map({
            //加载控件到地图容器中
            controls: defaultControls({
              zoom: false, //不显示放大缩小按钮
              rotate: false, //不显示指北针控件
            }).extend([new ScaleLine()]), //比例尺
            target: this.$refs.map, //目标容器
            layers: [
              new TileLayer({
                source: this.sourceMaoHeaderFn(),
              }),
            ],
            loadTilesWhileAnimating: true, //加载时的动画过度
            interactions: new defaults({
              doubleClickZoom: false,
            }),
            view: new View({
              //视口地图相关配置
              projection: "EPSG:3857", //3857为墨卡托坐标，4326为gps经纬度
              center: this.gisPosTransform1(this.centerCoodinate), //设置默认的视角中心点
              zoom: 4, //缩放级别
              minZoom: 2,
              maxZoom: 8,
            }),
          });
          this.forEachShipPointToMapFn();
          this.addPopUpInMapFn();
          this.setMapClickFn();
        }
      });
    },
    // 给source 添加请求头
    sourceMaoHeaderFn() {
      let source = new XYZ({
        url:
          process.env.VUE_APP_BASE_API +
          "/underwater-sound/maps/{z}/{x}/{y}.png",
      });
      source.setTileLoadFunction((tile, src) => {
        const xhr = new XMLHttpRequest();
        xhr.responseType = "blob";
        xhr.addEventListener("loadend", function (evt) {
          const data = this.response;
          if (data !== undefined) {
            tile.getImage().src = URL.createObjectURL(data);
          } else {
            tile.setState(TileState.ERROR);
          }
        });
        xhr.addEventListener("error", function () {
          tile.setState(TileState.ERROR);
        });
        xhr.open("GET", src);
        xhr.setRequestHeader(
          "Authorization",
          `Bearer ${this.$store.state.token}`
        );
        xhr.send();
      });
      return source;
    },
    // 经纬度转墨卡托坐标
    gisPosTransform1(pos) {
      console.log(pos, "EPSG:4326", "EPSG:3857");
      return transform(pos, "EPSG:4326", "EPSG:3857");
    },
    // 墨卡托转经纬度坐标
    gisPosTransform2(pos) {
      return transform(pos, "EPSG:3857", "EPSG:4326");
    },
    // 更新地图上的船只信息
    onUpdateMapShipInfoFn(item) {
      let source = this.shipLayer.getSource();

      let featureItem = null;
      source.forEachFeature((feature) => {
        if (feature.SHIPID === item.id) {
          featureItem = feature;
          return false;
        }
      });
      console.log(source, "source");
      console.log(item, "item");
      let newLonLatArr = this.gisPosTransform1([
        item.shipInfo[this.lon],
        item.shipInfo[this.lat],
      ]);
      featureItem.OPTIONSParams = item;
      featureItem.getGeometry().setCoordinates(newLonLatArr);
      this.isHideMapPopupFn();
      this.mapInstance.render();
      let data = {
        id: item.id,
        dataInfo: JSON.stringify(item.dataInfo),
      };

      this.$api.glpzRightTableItemUpdateApi(data).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "修改成功!",
          });
        }
      });
    },
    // 删除地图上的船只信息
    onDelMapShipInfoFn(item) {
      let source = this.shipLayer.getSource();
      let featureItem = null;
      source.forEachFeature((feature) => {
        if (feature.SHIPID === item.id) {
          featureItem = feature;
          return false;
        }
      });
      this.isHideMapPopupFn();
      source.removeFeature(featureItem);
      let data = [item.id];
      this.$api.glpzRightTableItemDelApi(data).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        }
      });
    },
    // 循环生成坐标点
    forEachShipPointToMapFn() {
      let featuresArr = this.mapShipList.map((item) => {
        return this.onDrawPointFn(item);
      });
      this.shipLayer = new VectorLayer({
        source: new VectorSource({
          features: featuresArr,
        }),
        style: null,
        name: "shipLayer ",
        visible: true,
      });
      this.mapInstance.addLayer(this.shipLayer);
    },
    // 绘制point
    onDrawPointFn(item) {
      let { dataInfo, id } = item;
      let tranPos = this.gisPosTransform1([
        dataInfo[this.lon],
        dataInfo[this.lat],
      ]);

      let point = new Point(tranPos);
      let feature = new Feature(point);

      feature.setStyle(this.pointColor());
      feature.SHIPID = id;
      feature.OPTIONSParams = item;
      return feature;
    },
    // point的样式
    pointColor() {
      return new Style({
        image: new Icon({
          anchor: [0.5, 46],
          scale: 0.7,
          anchorXUnits: "fraction",
          anchorYUnits: "pixels",
          src: shipPng,
        }),
      });
    },
    // 增加弹出窗
    addPopUpInMapFn() {
      this.popupObj = new Overlay({
        element: document.getElementById("ship_popup"),
        positioning: "center-right",
        stopEvent: false,
        offset: [-40, -12],
      });
      this.mapInstance.addOverlay(this.popupObj);
    },
    // 自定义事件的htmlBox
    diyThingHtmlBoxFn(item) {
      let { dataInfo, nameArr } = item;
      // 头部标题
      let titleBox = `<div class='ship_title'>船只信息</div>`;
      // 内容中的小盒子
      let smBoxes = []; // 用于存储所有smBox的数组

      // 使用for循环生成smBoxes
      for (let i = 0; i < nameArr.length; i++) {
        let smBox = `<div class='ship_item'>  
                      <div class='ship_item_name'>${nameArr[i]}</div>  
                      <div class='ship_item_val'>${dataInfo[nameArr[i]]}</div>  
                  </div>`;
        smBoxes.push(smBox); // 将每个smBox添加到数组中
      }

      // 使用数组的join方法将smBoxes组合成一个字符串
      let contentBox = `<div class='ship_list'>${smBoxes.join("")}</div>`;

      let triBox = `<div class='ship_tri'></div>`;

      // 将titleBox, contentBox, 和triBox组合成mainBox
      let mainBox = `${titleBox}${contentBox}${triBox}`;
      return mainBox;
    },
    // 地图的点击事件
    setMapClickFn() {
      this.mapInstance.on("click", (evt) => {
        const feature = this.mapInstance.forEachFeatureAtPixel(
          evt.pixel,
          function (feature) {
            return feature;
          }
        );
        if (feature) {
          // 设置弹窗位置并显示
          this.popupObj.setPosition(feature.getGeometry().getCoordinates());
          const element = this.popupObj.getElement();
          if (element) {
            element.innerHTML = this.diyThingHtmlBoxFn(feature.OPTIONSParams);
          }
        } else {
          this.popupObj.setPosition(undefined);
        }
      });
    },
    // 消除地图上的popup展示
    isHideMapPopupFn() {
      this.popupObj.setPosition(undefined);
    },
  },
};
</script>

<style lang="scss" scoped>
.map_dialog {
  display: flex;
  width: 100%;
  height: 840px;

  .map_left {
    flex: 1 1 auto;
    width: 0;
    height: 100%;
    margin-right: 10px;

    #map_box {
      width: 100%;
      height: 100%;
    }
  }

  .map_right {
    flex: 0 0 auto;
    width: 450px;
    height: 100%;
    border-left: 1px solid #02fff4;
    display: flex;
    flex-direction: column;

    .map_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex: 0 0 auto;
      width: 100%;
      height: 54px;
      line-height: 54px;
      box-sizing: border-box;
      padding: 0 32px;
      border-bottom: 1px solid #02fff4;
      color: #fff;
      font-size: 20px;
      background-color: rgba(2, 255, 244, 0.2);
      position: relative;

      &::after {
        content: "";
        background-color: #02fff4;
        position: absolute;
        width: 5px;
        height: 20px;
        left: 16px;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .map_list_wrap {
      flex: 1 1 auto;
      width: 100%;
      height: 0;
      box-sizing: border-box;
      padding: 0 4px;
      overflow: hidden;
      margin: 16px 0;

      ::v-deep .map_list {
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        padding: 0 16px;
        overflow: auto;

        .ship_collapse {
          border-color: transparent;

          .el-collapse-item {
            .el-collapse-item__header {
              color: #fff;
              background: rgba(0, 94, 123, 0.7);
              box-shadow: inset 0px 0px 12px 1px #02fff4;
              border: 1px solid #02fff4;
              box-sizing: border-box;
              padding: 0 20px;
              font-size: 20px;

              .map_items_title {
                width: 90%;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .items_title_icons {
                  display: flex;
                  align-items: center;

                  .title_icon_edit,
                  .title_icon_del {
                    font-size: 24px;
                    color: #fff;
                    margin: 0 5px;
                  }
                }
              }
            }

            .el-collapse-item__wrap {
              border-color: transparent;
              background-color: transparent;

              .el-collapse-item__content {
                background-color: transparent;

                .map_items_content {
                  .content_items {
                    display: flex;
                    align-items: center;
                    width: 100%;
                    height: 50px;
                    box-sizing: border-box;
                    border: 1px solid #02fff4;
                    font-size: 20px;
                    color: #fff;

                    .items_name {
                      flex: 0 0 auto;
                      width: 150px;
                      height: 100%;
                      border-right: 1px solid #02fff4;
                      line-height: 48px;
                      text-align: center;
                      background: rgba(1, 75, 97, 0.8);
                      padding: 0 12px;
                      box-sizing: border-box;
                      text-overflow: ellipsis;
                      overflow: hidden;
                      white-space: nowrap;
                    }

                    .items_val {
                      flex: 1 1 auto;
                      width: 0;
                      line-height: 48px;
                      padding: 0 12px;
                      background-color: rgba(2, 26, 39, 0.5);
                      box-sizing: border-box;
                      text-overflow: ellipsis;
                      overflow: hidden;
                      white-space: nowrap;

                      .ship_input {
                        &.is-disabled {
                          .el-input__inner {
                            background: transparent;
                            border-color: transparent;
                            color: #fff;
                            cursor: default;
                          }
                        }

                        .el-input__inner,
                        .el-textarea__inner {
                          background-color: transparent;
                          border-color: transparent;
                          color: #fff;
                          font-size: 20px;
                          padding: 0;
                        }
                      }
                    }
                  }

                  .content_items_btns {
                    display: flex;
                    align-items: center;
                    width: 100%;
                    height: 50px;
                    box-sizing: border-box;
                    border: 1px solid #02fff4;
                    font-size: 20px;
                    color: #fff;
                    justify-content: center;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  ::v-deep #ship_popup {
    width: 380px;
    background: rgba(7, 47, 70, 0.9);
    border: 1px solid #02fff4;
    box-sizing: border-box;
    position: relative;

    .ship_title {
      width: 100%;
      height: 54px;
      box-sizing: border-box;
      padding: 0 18px;
      line-height: 54px;
      background: rgba(2, 255, 244, 0.2);
      font-size: 20px;
      color: #fff;
    }

    .ship_list {
      box-sizing: border-box;
      padding: 20px;

      .ship_item {
        font-size: 18px;
        color: #02fff4;
        display: flex;
        align-items: center;
        margin-top: 8px;

        &:first-child {
          margin-top: 0;
        }

        .ship_item_name {
          flex: 0 0 auto;
          width: 90px;
        }

        .ship_item_val {
          flex: 1 1 auto;
          width: 100%;
          height: 44px;
          line-height: 42px;
          background: rgba(2, 69, 93, 0.6);
          border: 1px solid rgba(2, 255, 244, 0.6);
          box-sizing: border-box;
          padding: 0 18px;
        }
      }
    }

    .ship_tri {
      position: absolute;
      top: 50%;
      right: -28px;
      transform: translateY(-50%);
      border: 15px solid transparent;
      border-left-color: rgba(7, 47, 70, 0.9);
    }
  }
}
</style>
